package com.opages.netty.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author daizhong.liu
 * @create 2021-12-06 17:54
 **/
public class HttpNettyServerDemo {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new CustomChannelHandler());
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.addListener(listener -> {
               if(listener.isSuccess()) {
                   System.err.println("启动完成..");
               }else  {
                   System.err.println("启动失败!");
               }
            });
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class CustomChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("httpServerCodec",new HttpServerCodec())
                    .addLast(new CustomHttpServerHandler());
        }

    }
    private static class CustomHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            if(msg instanceof HttpRequest) {
                HttpRequest request = (HttpRequest)msg;
                String uri = request.uri();
                System.err.println("浏览器地址："+uri);
                ByteBuf responseMsg = Unpooled.wrappedBuffer("服务端回复浏览器消息.".getBytes(CharsetUtil.UTF_8));
                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,responseMsg);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, responseMsg.readableBytes());
                ctx.writeAndFlush(response);
            }
        }
    }
}
